<template>
 <div class="account-wrap">
    <div class="box">
      <h5 class="title">
        <span>账号管理</span>
      </h5>
      <ul class="info-list">
        <li class="info-item"
          v-if="userInfo.PhoneNumber">
          <div class="info-left">
            <svg-icon iconClass="password" />
            <span class="label">登录密码</span>
            <span :class="{'no-set': !userInfo.HasSetPwd}"> {{ userInfo.HasSetPwd ? '******' : '---' }}</span>
          </div>
          <el-button class="btn-mini-grey"
            size="mini"
            @click="onUpdatePwd()">{{userInfo.HasSetPwd ? '修改' : '设置'}}密码</el-button>
        </li>
        <li class="info-item">
          <div class="info-left">
            <svg-icon iconClass="phone" />
            <span class="label">手机号码</span>
            <span v-if="userInfo.PhoneNumber">{{userInfo.PhoneNumber | formatPhone}}</span>
            <span v-else
              class="no-set">---</span>
          </div>
          <el-button class="btn-mini-grey"
            size="mini"
            @click="onBindPhone()">{{userInfo.PhoneNumber ? '更换' : '绑定'}}手机</el-button>
        </li>
        <li class="info-item">
          <div class="info-left">
            <svg-icon class="wx"
              iconClass="wechat" />
            <span class="label">微信账号</span>
            <span :class="{'no-set': !userInfo.HasBindWx}">{{ userInfo.HasBindWx ? userInfo.wx_nick||'已绑定' : '---' }}</span>
          </div>
          <el-button class="btn-mini-grey"
            size="mini"
            :class="{disable: unbindWxDisabled}"
            @click="onBindWx">{{userInfo.HasBindWx ? '解绑' : '绑定'}}微信</el-button>
        </li>
      </ul>
    </div>
    <div class="box device">
      <h5 class="title">
        <span>设备管理</span>
        <span class="title-right" @click="getDeviceList" >
          <svg-icon iconClass="refresh"/>
          刷新
        </span>
      </h5>
      <ul class="info-list">
        <li class="device-item">
          <span>设备名称</span>
          <span class="header-time">登录时间</span>
        </li>
        <li v-for="item in deviceList"
          :key="item.device_id"
          class="device-item"
          :class="{active:item.device_id===appInfo.uuid}">
          <span class="device-name">
            <span>{{ item.device_name }}</span>
            <svg-icon icon-class="dev-edit"
              @click="renameDevice(item)" />
            <span v-if="item.device_id===appInfo.uuid" class="active-tips">当前设备</span>
          </span>
          <span class="login-time">{{ item.updated_at | parseTime }}</span>
          <el-button class="btn-mini-grey"
            size="mini"
            @click="loginoutDevice(item)">退出登录</el-button>
        </li>
      </ul>
    </div>
    <div class="box logoff" v-if="appInfo.merchant==='xz'">
      <span class="logoff-btn" @click="openInner">注销账号</span>
    </div>
    <el-dialog custom-class="inner-dialog dialog-offset"
      :visible.sync="showInnerDialog"
      :modal-append-to-body="false"
      :close-on-click-modal="false"
      top="20vh"
      width="480px">
      <template #title>
        <span class="xz-confirm-title">
          <svg-icon :iconClass="appCfg.logo"/>
          {{appCfg.name}}
        </span>
      </template>
      <div class="inner-body">
        <svg-icon iconClass="error" />
        <div class="cancel-wrap">
          <p>
            <span>注销后会清空以下</span><span class="txt-warning">
              <template v-if="productList.length">产品（{{ productList.length }}个）的信息和数据</template>
              <template v-else>所有产品的信息和数据</template>
            </span>
            <span>，确定注销？</span>
          </p>
          <p class="label">(包括手机端和电脑端)</p>
        </div>
      </div>
      <div class="product-box" v-loading="productLoading" element-loading-background="rgba(0, 0, 0, 0)">
        <span class="product-item" v-for="(it, i) in productList" :key="i">
          <img :src="it.icon" alt="">
          {{ it.name }}
        </span>
      </div>
      <div class="inner-tips">请确保所有记录和交易已完结无纠纷，认同注销即为数据可丢弃，请谨慎操作</div>
      <div class="inner-footer">
        <el-checkbox v-model="protocalChecked"><span @click="openUrl" class="link">已阅读并同意<em>《注销协议》</em></span></el-checkbox>
        <div class="btn-wrap">
          <el-button @click="delUser"
            type="primary"
            size="small">确定</el-button>
          <el-button @click="showInnerDialog = false"
            size="small">取消</el-button>
        </div>
      </div>
    </el-dialog>
    <el-dialog
      :visible.sync="showBindWx"
      customClass="dialog-offset login-dialog"
      top="20vh"
      :close-on-click-modal="false"
      width="350px">
      <BindWx v-if="showBindWx" ref="bindWx" @completeBind="showBindWx = false" @needMerge="needMerge"/>
    </el-dialog>
    <el-dialog
      :visible.sync="showBindPhone"
      customClass="dialog-offset login-dialog"
      top="15vh"
      :close-on-click-modal="false"
      width="350px"
      >
      <BindPhone ref="bindPhone" :visible="showBindPhone" @completeBind="showBindPhone = false" @needMerge="needMerge"/>
    </el-dialog>
    <BindMerge :visible.sync="mergeVisible"
      :data="mergeData"
      :fromBindType="bindType"
      @completeBind="mergeComplete" />
    <el-dialog
      :visible.sync="showUpdatePwd"
      customClass="dialog-offset login-dialog"
      top="8vh"
      :close-on-click-modal="false"
      width="350px"
      @closed="onUpdatePwdClose">
      <UpdatePwd ref="updatePwd" isUpdatePwd :visible="showUpdatePwd" @completeUpdatePwd="showUpdatePwd = false"/>
    </el-dialog>
  </div>
</template>
<script>
import { mapGetters } from 'vuex'
import BindMerge from './components/bind-merge'
import BindPhone from './components/bind-phone'
import UpdatePwd from '@/components/account/update-pwd'
import BindWx from './components/bind-wx'
import { oath2Unbind } from '@/api/login'
import { getDeviceList, renameDevice, delDevice, delUser, getAllApp } from '@/api/user'
export default {
  name: 'SecurityCenter',
  components: {
    BindPhone,
    BindMerge,
    BindWx,
    UpdatePwd
  },
  data () {
    return {
      deviceList: [],
      showBindWx: false, // 绑定微信弹窗
      showBindPhone: false, // 绑定手机弹窗
      mergeVisible: false, // 合并账号弹窗
      showUpdatePwd: false, // 更改密码弹窗
      // 修改设备名等弹窗
      showInnerDialog: false,
      // 注销协议勾选
      protocalChecked: false,
      productLoading: false,
      productList: [],
      mergeData: {},
      bindType: ''
    }
  },
  computed: {
    ...mapGetters(['userInfo', 'appInfo', 'appCfg']),
    /** 解绑微信禁用 */
    unbindWxDisabled () {
      return this.userInfo.HasBindWx && !this.userInfo.PhoneNumber
    }
  },
  watch: {
    'userInfo.user_id': {
      handler (val) {
        if (!val) {
          this.showBindPhone = false
          this.showBindWx = false
          this.mergeVisible = false
          this.showInnerDialog = false
          this.showUpdatePwd = false
        }
      }
    }
  },
  created () {
    this.getDeviceList()
  },
  methods: {
    openUrl () {
      this.$xz('xz_open_url', `${this.appCfg.site}/logoff-protocol.html`)
    },
    getDeviceList () {
      getDeviceList({ 'uuid': this.appInfo.uuid }).then(res => {
        this.deviceList = res.data
      })
    },
    onBindPhone () {
      this.showBindPhone = true
    },
    // onBindPhoneClose () {
    //   this.$refs.bindPhone.resetFields()
    // },
    onUpdatePwd () {
      this.showUpdatePwd = true
    },
    onUpdatePwdClose () {
      this.$refs.updatePwd.resetFields()
    },
    onBindWx () {
      const { HasBindWx } = this.userInfo
      if (HasBindWx) {
        this.unBindWx()
      } else {
        this.showBindWx = true
      }
    },
    mergeComplete () {
      this.showBindPhone = false
      this.showBindWx = false
      this.mergeVisible = false
    },
    /** 微信解绑 */
    unBindWx () {
      this.$PsMessageBox({
        iconClass: 'error',
        center: true,
        message: '确定要解除微信绑定？'
      }).then(() => {
        this.$xz('xz_substat_action', 1742)
        oath2Unbind({ 'type': 'wx' }).then(res => {
          this.$store.dispatch('user/getUserInfo')
          this.$PsMessage({ message: '微信解绑成功！', iconClass: 'success', offset: 270 })
        })
      })
    },
    /** 注销 */
    delUser () {
      if (!this.protocalChecked) {
        this.$PsMessage({ message: '请勾选注销协议！', offset: 270 })
        return
      }
      this.$xz('xz_substat_action', 1738)
      delUser({ 'uuid': this.appInfo.uuid }).then(res => {
        this.showInnerDialog = false
        this.$store.dispatch('user/resetUserInfo')
        this.$router.push('/usercenter')
        this.$xz('xz_delete_account')
      })
    },
    /** 设备重命名 */
    renameDevice (item) {
      this.$PsMessageBox.prompt('设备重命名：', {
        inputValue: item.device_name,
        beforeClose: (action, instance, done) => {
          if (action === 'confirm') {
            this.$xz('xz_substat_action', 1743)
            instance.confirmButtonLoading = true
            renameDevice({ id: item.id, name: instance.inputValue }).then(res => {
              this.getDeviceList()
              done()
            }).finally(() => {
              instance.confirmButtonLoading = false
            })
          } else {
            done()
          }
        },
        inputValidator: value => {
          if (!value) return '设备名不能为空'
          // eslint-disable-next-line no-control-regex
          const str = value.replace(/[^\x00-\xff]/g, '01')
          if (str.length > 30) return '设备名已超过最长限制'
          return true
        }
      })
    },
    /** 设备退出登录 */
    loginoutDevice (item) {
      this.$PsMessageBox({
        iconClass: 'error',
        message: `确定退出登录该设备${item.device_name}？`
      }).then(() => {
        this.$xz('xz_substat_action', 1744)
        delDevice(item.id).then(res => {
          if (item.device_id === this.appInfo.uuid) {
            this.$store.dispatch('user/resetUserInfo')
            this.$router.push('/usercenter')
          } else {
            this.getDeviceList()
          }
        })
      })
    },
    needMerge (data, type) {
      this.mergeData = data
      this.bindType = type
      this.$xz('xz_substat_action', 1784)
      this.mergeVisible = true
    },

    /** 打开注销确认框 */
    openInner () {
      this.productList = []
      this.productLoading = true
      getAllApp()
        .then(res => {
          this.productList = (res?.data?.list || []).filter(it => it.used)
          this.productLoading = false
        })
        .finally(() => {
          // this.productLoading = false
        })
      this.showInnerDialog = true
    }
  }
}
</script>
<style lang="scss" scoped>
.account-wrap {
  display: flex;
  flex-direction: column;
  height: 100%;
  color: #fff;
  font-size: 12px;
}
.box {
  padding-top: 20px;
  &:first-child{
    padding-top: 0;
  }
  .title {
    display: flex;
    justify-content: space-between;
    margin-bottom: 4px;
    border-bottom: 1px solid #47484b;
    height: 32px;
    font-weight: bold;
    font-size: 14px;
  }
  .title-right {
    font-size: 12px;
    font-weight: 400;
  }
  .info-list {
    margin-left: 10px;
  }
  .info-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    box-sizing: content-box;
    padding-top: 10px;
    height: 24px;
    font-size: 12px;
  }
  .info-left {
    display: flex;
    align-items: center;
    height: 100%;
    .svg-icon {
      font-size: 20px;
      &.wx {
        color: #44b820;
      }
    }
    .label {
      color: #999;
      margin: 0 20px 0 5px;
    }
    .no-set {
      color: #999;
    }
  }
  &.device {
    flex: 1;
    .title {
      .title-right {
        height: 100%;
        padding-top: 7px;
        cursor: pointer;
        &:hover {
          color: #00cce9;
        }
      }
      .svg-icon {
        font-size: 16px;
      }
    }
    .device-item {
      position: relative;
      display: flex;
      align-items: center;
      color: rgba(255, 255, 255, 0.6);
      font-size: 12px;
      padding-top: 8px;
      &.active {
        color: #fff;
        &::before {
          position: absolute;
          left: -10px;
          content: "";
          width: 6px;
          height: 6px;
          background: #49d61c;
          border-radius: 50%;
        }
        .btn-mini-grey{
          border-color: #00BBD7;
          background-color: transparent;
          color: #00BBD7;
          &:hover{
            background-color: #00BBD7;
            color: #fff;
          }
        }
      }
      .header-time {
        position: absolute;
        right: 143px;
      }
      .device-name {
        flex: 1;
        display: flex;
        align-items: center;
        overflow: hidden;
        span {
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
        }
        .svg-icon {
          margin-left: 2px;
          color: #999;
          font-size: 16px;
          cursor: pointer;
          &:hover {
            color: #00cce9;
          }
        }
        .active-tips{
          margin-left: 5px;
          padding: 2px 5px;
          background: #00BBD7;
          border-radius: 4px;
        }
      }
      .login-time {
        width: 100px;
        min-width: 100px;
        margin: 0 20px 0 30px;
      }
      .right-btn {
        color: #fff;
        cursor: pointer;
        &:hover {
          color: #00cce9;
        }
      }
    }
  }
  &.logoff {
    padding-bottom: 14px;
    text-align: center;
    .logoff-btn{
      font-size: 12px;
      color: #999;
      cursor: pointer;
      &:hover{
        color: #F84D4D;
      }
    }
  }
}
.account-wrap /deep/.inner-dialog .el-dialog__body{
  padding: 20px 34px 24px;
}
.inner-body {
  display: flex;
  align-items: center;
  .svg-icon {
    flex-shrink: 0;
    font-size: 32px;
    margin-right: 5px;
  }
  .cancel-wrap {
    color: #fff;
    .txt-warning {
      color: #FF7373;
      font-weight: bold;
    }
    .label {
      color: rgba(255, 255, 255, 0.7);
      margin-top: 4px;
    }
  }
}
.product-box{
  display: flex;
  // justify-content: space-between;
  position: relative;
  // height: 74px;
  min-height: 62px;
  flex-wrap: wrap;
  // width: 370px;
  // padding: 31px 31px 24px;
  padding: 14px 15px;
  margin: 20px auto 0;
  border: 1px solid #505050;
  border-radius: 4px;
  .product-item{
    // min-width: 33.333%;
    padding: 6px 15px;
    img{
      width: 20px;
      height: 20px;
      vertical-align: -0.3em;
    }
  }
}
.inner-tips{
  font-size: 12px;
  margin: 12px 0 23px;
  color: rgba(255, 255, 255, .5);
}
.inner-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 12px;
}
.link{
  color: #fff;
  cursor: pointer;
  em{
    color: #00cce9;
  }
  &:hover {
    text-decoration: underline;
  }
}
</style>
<style lang="scss">
.btn-wrap {
  .el-button {
    min-width: 80px;
    padding-left: 6px;
    padding-right: 6px;
  }
}
</style>
